#include <stdexcept>
#include <cstring>

#include "FileSegmentHeader.h"


FileSegmentHeader::FileSegmentHeader(const std::string& pFileName,
	const uint32_t& pSegmentNum) :
	fileName(pFileName), segmentNum(pSegmentNum)
{}


size_t FileSegmentHeader::size() const
{
	return sizeof(uint32_t)*2+fileName.size();
}


void FileSegmentHeader::write_to(char* buffer, size_t bufferSize) const
{
	if (bufferSize < size())
		throw std::invalid_argument("buffer is too small");

	const uint32_t fileNameSize = fileName.size();
	
	memcpy(buffer, &segmentNum, sizeof(uint32_t));
	buffer += sizeof(uint32_t);

	memcpy(buffer, &fileNameSize, sizeof(uint32_t));
	buffer += sizeof(uint32_t);
	
	memcpy(buffer, fileName.data(), fileName.size());
}


void FileSegmentHeader::read_from(const char* buffer, size_t bufferSize)
{
	uint32_t fileNameSize;

	if (bufferSize < sizeof(uint32_t)*2)
		throw std::invalid_argument("buffer is too small");

	memcpy(&segmentNum, buffer, sizeof(uint32_t));
	buffer += sizeof(uint32_t);

	memcpy(&fileNameSize, buffer, sizeof(uint32_t));
	buffer += sizeof(uint32_t);

	fileName.assign(buffer, std::min<uint32_t>(fileNameSize,
			bufferSize-sizeof(uint32_t)*2));
}
